<!--图文管理-->
<template>
  <div id="thirdWechatArticle" class="app-container">
    <!--搜索条件-->
    <div class="filter-container">
      <el-form :model="listQuery" :inline="true">
        <el-form-item v-if="mode==='editor'" label="应用：">
          <application-key-select v-model="listQuery.appId" :type="listQuery.type" />
        </el-form-item>
        <el-form-item label="分类：">
          <el-select v-model="listQuery.categoryId" placeholder="请选择素材分类" @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题：">
          <el-input v-model="listQuery.keyword" clearable placeholder="请输入文章标题" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="作者：">
          <el-input v-model="listQuery.author" clearable placeholder="请输入作者" @keyup.enter.native="handleFilter" />
        </el-form-item>
        <el-form-item label="发布时间：">
          <div class="flex-row">
            <el-date-picker v-model="listQuery.startDate" style="flex: 1;" type="datetime" value-format="timestamp" placeholder="请选择" clearable />
            <span style="padding: 0 10px;">至</span>
            <el-date-picker v-model="listQuery.endDate" style="flex: 1;" type="datetime" value-format="timestamp" placeholder="请选择" clearable />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" plain @click="handleFilter">搜索</el-button>
          <el-button icon="el-icon-refresh" plain @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--列表-->
    <div class="table-container flex-main">
      <div v-if="mode==='editor'" class="table-container-header">
        <table-toolbar create-text="发布新闻" :remove="status==='3'" remove-text="彻底删除" @create="handleCreate" @refresh="handleFilter" @remove="removeRecord" />
      </div>
      <div v-if="mode==='select'" class="table-container-header">
        <el-button type="primary" plain @click="handleSelect">选择</el-button>
      </div>
      <el-tabs v-if="mode==='editor'" v-model="status" class="common-tabs" @tab-click="handleTabClick">
        <el-tab-pane label="所有" name="-1" />
        <el-tab-pane label="待发布" name="1" />
        <el-tab-pane label="已发布" name="2" />
        <el-tab-pane label="草稿" name="0" />
        <el-tab-pane label="回收站" name="3" />
      </el-tabs>
      <el-table
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        height="100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column type="selection" width="60" />
        <el-table-column align="center" prop="id" label="#" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>
        <el-table-column label="封面" prop="avatar" width="70" align="center">
          <template slot-scope="scope">
            <img :src="common.getFileView(scope.row.photo)" class="common-round-image-32" @error="handleImageError">
          </template>
        </el-table-column>
        <el-table-column label="标题" prop="title" min-width="330" show-overflow-tooltip>
          <template slot-scope="scope">
            <div class="color-primary common-cursor" style="margin-left: 5px;font-size: 14px;font-weight: bold;" @click="handleLook(scope.row.id)">{{ scope.row.title }}</div>
            <div class="color-default">
              <el-tag v-if="scope.row.isDeleted===1" style="margin-right: 5px;" size="mini" type="danger"> 回收站</el-tag>
              <el-tag v-if="scope.row.status===1" style="margin-right: 5px;" size="mini" type="info"> 待发布</el-tag>
              <el-tag v-if="scope.row.status===2" style="margin-right: 5px;" size="mini" type="primary"> 已发布</el-tag>
              <el-tag v-if="scope.row.status===0" style="margin-right: 5px;" size="mini" type="warning"> 草稿</el-tag>
              <span>
                <template v-if="scope.row.leavingMessage===0">禁止留言</template>
                <template v-if="scope.row.leavingMessage===1">所有人可留言</template>
                <template v-if="scope.row.leavingMessage===2">仅粉丝可留言</template>
              </span>
              <span v-if="scope.row.isOriginal==0" style="margin-left:5px" class="color-danger">摘抄自:{{ scope.row.source }}</span>
              <span v-if="scope.row.isOriginal==1" style="margin-left:5px" class="color-primary">原创</span>
              <span style="margin-left:5px">作者：{{ scope.row.author }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="publishDate" sortable label="发布日期" width="160">
          <template slot-scope="scope">
            {{ scope.row.publishDate | formatDate('yyyy-MM-dd hh:mm') }}<br>
          </template>
        </el-table-column>
        <el-table-column label="浏览" width="70" prop="viewCount" sortable />
        <el-table-column label="评论" width="70" prop="commentCount" sortable />
        <el-table-column label="收藏" width="70" prop="collectCount" sortable />
        <el-table-column label="点赞" width="70" prop="likeCount" sortable />
        <el-table-column label="操作" align="center" fixed="right" width="120">
          <template slot-scope="scope">
            <template v-if="mode==='editor'">
              <template v-if="scope.row.isDeleted===1">
                <button-option icon="el-icon-refresh-right" skin="default" title="从回收站恢复" @click="handleRecovery(scope.row)" />
                <button-option icon="el-icon-delete" skin="danger" title="彻底删除" @click="handleRemoveSingle(scope.row)" />
              </template>
              <template v-else>
                <button-option v-if="scope.row.status!==2" icon="el-icon-edit" skin="primary" title="文章编辑" @click="handleUpdate(scope.row)" />
                <button-option v-if="[2].includes(scope.row.status)" icon="iconQrcode" icon-type="svg" skin="primary" title="二维码" @click="handleQrcode(scope.row)" />
                <button-option v-if="[1].includes(scope.row.status)" icon="el-icon-s-promotion" skin="primary" title="发布上线" @click="handleRelease(scope.row)" />
                <button-option v-if="[2].includes(scope.row.status)" icon="el-icon-refresh-left" skin="danger" title="撤销发布" @click="handleRevokePublication(scope.row)" />
                <button-option icon="el-icon-brush" skin="warning" title="移入回收站" @click="handleMoveRecycleBin(scope.row)" />
              </template>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination_handler">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    </div>
    <model-dialog
      title="H5二维码"
      :visible.sync="dialogVisible"
      width="220px"
      :show-close="false"
      @close="dialogVisible=!dialogVisible">
      <div class="preview-qrcode-container">
        <div id="qrCode" ref="qrCodeDiv" class="qrcode" />
        <div class="scan-tip">手机扫码预览</div>
      </div>
    </model-dialog>
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import applicationKeySelect from '@/views/third/applicationKeySelect'
export default {
  components: { applicationKeySelect },
  props: {
    mode: {
      type: String,
      default: 'editor'
    },
    appId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      status: '-1',
      categories: [],
      list: [],
      total: 0,
      listQuery: {
        appId: '',
        type: 1,
        page: 1,
        categoryId: '',
        author: null,
        startDate: '',
        endDate: '',
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      },

      multipleSelectionRecords: [],
      dialogVisible: false
    }
  },
  watch: {
    appId: function(value) {
      this.listQuery = {
        ...this.listQuery,
        appId: value
      }
    },
    'listQuery.appId': function(val) {
      this.fetchData()
      this.fetchCategories()
    }
  },
  created() {
    if (this.appId) {
      this.listQuery = {
        ...this.listQuery,
        appId: this.appId
      }
    }
  },
  methods: {
    handleLook(id) {
      this.$router.push({ name: 'materialLibraryImageTextDetails', params: { id: id }})
    },
    handleTabClick() {
      if (this.status === '3') {
        this.listQuery = {
          ...this.listQuery,
          isDeleted: 1,
          status: null
        }
      } else if (this.status === '-1') {
        this.listQuery = {
          ...this.listQuery,
          isDeleted: 0,
          status: null
        }
      } else {
        this.listQuery = {
          ...this.listQuery,
          status: this.status,
          isDeleted: 0
        }
      }
      this.fetchData()
    },
    async fetchCategories() {
      var res = await this.$store.dispatch('thirdWechatResourceCategoryTree', { appId: this.listQuery.appId, type: 4 })
      this.categories = res
    },
    // 表格自带方法开始
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格行数据单击*/
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    /* 搜索*/
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    /* 重置*/
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT,
        categoryId: '',
        author: null,
        startDate: '',
        endDate: ''
      }
      this.fetchData()
    },
    async fetchData() {
      if (this.mode === 'editor') {
        this.listQuery = {
          ...this.listQuery,
          resourceType: 4

        }
      } else {
        this.listQuery = {
          ...this.listQuery,
          status: 2,
          resourceType: 4
        }
      }

      const response = await this.$store.dispatch('thirdWechatArticlePage', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    /* 新增*/
    handleCreate() {
      this.$router.push({ name: 'materialLibraryImageTextCreate', params: { appId: this.listQuery.appId }})
    },

    /* 编辑*/
    handleUpdate(row) {
      this.$router.push({ name: 'materialLibraryImageTextCreate', params: { appId: this.listQuery.appId }, query: { id: row.id }})
    },
    // 发布
    handleRelease(row) {
      this.$confirm(`您确定要发布【${row.title}】, 是否继续?`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('thirdWechatArticleRelease', [row.id]).then(response => {
          this.fetchData()
          this.$modal.msgSuccess('发布成功')
        }).catch(() => {})
      }).catch(() => { })
    },
    // 撤销发布
    handleRevokePublication(row) {
      this.$confirm(`您确定要撤销发布的【${row.title}】, 是否继续?`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('thirdWechatArticleRevokePublication', [row.id]).then(response => {
          this.fetchData()
          this.$modal.msgSuccess('撤销成功')
        }).catch(() => {})
      }).catch(() => { })
    },
    // 恢复
    handleRecovery(row) {
      this.$confirm(`您确定要从回收站中恢复【${row.title}】, 是否继续?`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('thirdWechatArticleRecovery', [row.id]).then(response => {
          this.fetchData()
          this.$modal.msgSuccess('恢复成功')
        }).catch(() => {})
      }).catch(() => { })
    },
    // 移入回收站
    handleMoveRecycleBin(row) {
      this.$confirm(`您确定要将【${row.title}】移入回收站, 是否继续?`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('thirdWechatArticleMoveRecycleBin', [row.id]).then(response => {
          this.fetchData()
          this.$modal.msgSuccess('移入回收站成功')
        }).catch(() => {})
      }).catch(() => { })
    },
    handleQrcode(row) {
      this.dialogVisible = true
      this.$nextTick(() => {
        document.getElementById('qrCode').innerHTML = ''
        new QRCode(this.$refs.qrCodeDiv, { //
          text: this.T.getUrl() + '#/wxPubArticle/h5/preview/' + row.id,
          width: 120,
          height: 120,
          colorDark: '#333333', // 二维码颜色
          colorLight: '#ffffff', // 二维码背景色
          correctLevel: QRCode.CorrectLevel.L// 容错率，L/M/H
        })
      })
    },

    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('thirdWechatArticleRemove', ids).then(response => {
            this.handleReset()
            this.$modal.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.$modal.msgWarning('请选择要删除的记录')
      }
    },
    handleSelect() {
      if (this.multipleSelectionRecords.length === 0) {
        this.$modal.msgWarning('请选择数据')
      } else if (this.multipleSelectionRecords.length > 8) {
        this.$modal.msgWarning('最多只能选择8条数据')
      } else {
        this.$emit('select', this.multipleSelectionRecords)
      }
    }

  }
}
</script>
<style lang="scss" scoped>
</style>
